package cn.ycxy.lbl.member.consumer;

import cn.ycxy.lbl.pojo.member.domain.User;
import com.easemob.im.server.EMService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class IMRegisterConsumer {
    public static final String CS_MEMBER_EX = "cs_member_ex";
    public static final String CS_MEMBER_IM_QUEUE = "cs_member_im_queue";
    public static final String CS_MEMBER_IM_REGISTER_RK = "cs_member_im_queue";

    @Autowired
    private EMService emService;

    @RabbitListener(bindings = @QueueBinding( // 队列绑定交换机
            value = @Queue(CS_MEMBER_IM_QUEUE), // 创建队列
            exchange = @Exchange(value = CS_MEMBER_EX, type = ExchangeTypes.DIRECT), // 创建交换机
            key = CS_MEMBER_IM_REGISTER_RK // 路由分组,
    ))
    public void listenDirectQueue2(User user) {
        log.info("IM新用户注册, 手机号为: {}", user.getPhone());
        String username = "im" + user.getPhone();
        //注册环信IM chat服务
        emService.user().create(username, user.getPassword()).block();
        Map<String, String> map = new HashMap<>();
        map.put("nickname", user.getNickname());
        map.put("avatar", user.getAvatar());
        map.put("phone", user.getPhone());
        //设置 其他属性
        emService.metadata().setMetadataToUser(username, map).block();
        log.info("注册并设置属性完毕!");
    }
}
